<template>
    <div class="gen-business-page art-full-height">
        <!-- 搜索栏 -->
        <GenBusinessSearch v-show="showSearchBar" v-model="searchForm" @search="handleSearch" @reset="handleReset" />

        <ElCard class="art-table-card" shadow="never" :style="{ 'margin-top': showSearchBar ? '12px' : '0' }">
            <!-- 表格头部 -->
            <ArtTableHeader v-model:columns="columnChecks" v-model:showSearchBar="showSearchBar" :loading="loading"
                @refresh="refreshData">
                <template #left>
                    <ElSpace wrap>
                        <ElButton v-auth="'add'" type="primary" @click="showDialog('add')" v-ripple>新增业务</ElButton>
                        <ElButton v-auth="'table'" type="danger" @click="openImportDialog" v-ripple>导入表格</ElButton>
                    </ElSpace>
                </template>
            </ArtTableHeader>

            <!-- 表格 -->
            <ArtTable rowKey="id" :loading="loading" :data="data" :columns="columns" :pagination="pagination"
                @pagination:size-change="handleSizeChange" @pagination:current-change="handleCurrentChange" />

            <!-- 业务新增/编辑弹窗 -->
            <GenBusinessDialog v-model:visible="dialogVisible" :type="dialogType" :editData="currentData"
                @submit="handleDialogSubmit" />

            <!-- 字段查看抽屉 -->
            <GenColumnDrawer v-model:visible="columnDrawerVisible" :business-id="currentBusinessId" />

            <!-- 导入表格弹窗 -->
            <GenImportDialog v-model:visible="importDialogVisible" @submitted="handleImportSubmitted" />
        </ElCard>
    </div>
</template>

<script setup lang="ts">
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { useTable } from '@/composables/useTable'
import { fetchGenBusinessList, deleteGenBusiness } from '@/api/code_generator/gen_business'
import type { GenBusiness } from '@/api/code_generator/gen_business'
import GenBusinessSearch from './modules/gen-business-search.vue'
import GenBusinessDialog from './modules/gen-business-dialog.vue'
import GenColumnDrawer from './modules/gen-column-drawer.vue'
import GenImportDialog from './modules/gen-import-dialog.vue'

defineOptions({ name: 'GenBusiness' })

const showSearchBar = ref(false)

// 搜索表单
const searchForm = ref<Record<string, any>>({
    app_name: undefined,
    table_name: undefined,
    keyword: undefined
})

const {
    data,
    columns,
    columnChecks,
    loading,
    pagination,
    refreshData,
    handleSizeChange,
    handleCurrentChange,
    searchParams,
    getData
} = useTable({
    core: {
        apiFn: fetchGenBusinessList,
        apiParams: {
            current: 1,
            size: 20,
            ...searchForm.value
        },
        immediate: false,
        columnsFactory: () => [
            { prop: 'id', label: 'ID', width: 80 },
            { prop: 'app_name', label: '应用名称' },
            { prop: 'table_name', label: '表名称' },
            { prop: 'doc_comment', label: '文档注释' },
            { prop: 'class_name', label: '基础类名' },
            { prop: 'schema_name', label: '模型类名' },
            { prop: 'filename', label: '文件名' },
            { prop: 'api_version', label: 'API 版本' },
            { prop: 'gen_path', label: '生成路径' },
            { prop: 'remark', label: '备注' },
            { prop: 'create_time', label: '创建时间', checked: false },
            {
                prop: 'operation',
                label: '操作',
                width: 165,
                aglin: 'right',
                formatter: (row) =>
                    h('div', [
                        h(ArtButtonTable, {
                            type: 'view',
                            onClick: () => showDialog('view', row as GenBusiness)
                        }),
                        h(ArtButtonTable, {
                            type: 'edit',
                            onClick: () => showDialog('edit', row as GenBusiness)
                        }),
                        h(ArtButtonTable, {
                            type: 'delete',
                            onClick: () => handleDelete(row)
                        })
                    ])
            }
        ]
    }
})

// 处理搜索与重置
const handleSearch = (params: Record<string, any>) => {
    const keys = ['app_name', 'table_name', 'keyword']
    const sp = searchParams as Record<string, any>
    keys.forEach((k) => {
        sp[k] = params[k] ?? undefined
    })
    searchParams.current = 1
    getData()
}

const handleReset = () => {
    const keys = ['app_name', 'table_name', 'keyword']
    const sp = searchParams as Record<string, any>
    keys.forEach((k) => delete sp[k])
    searchParams.current = 1
    getData()
}

// 弹窗相关
const dialogType = ref<'add' | 'edit'>('add')
const dialogVisible = ref(false)
const currentData = ref<GenBusiness | undefined>(undefined)

// 抽屉相关
const columnDrawerVisible = ref(false)
const currentBusinessId = ref(0)
const importDialogVisible = ref(false)

const showDialog = (type: 'add' | 'edit' | 'view', row?: GenBusiness) => {
    if (type === 'view') {
        if (row?.id) {
            currentBusinessId.value = row.id
            columnDrawerVisible.value = true
        }
    } else {
        dialogType.value = type
        currentData.value = row || ({} as GenBusiness)
        dialogVisible.value = true
    }
}

const openImportDialog = () => {
    importDialogVisible.value = true
}

const handleImportSubmitted = () => {
    // 导入成功后刷新业务列表
    refreshData()
}

const handleDialogSubmit = async () => {
    dialogVisible.value = false
    currentData.value = {} as GenBusiness
    refreshData()
}

// 删除
const handleDelete = async (row: GenBusiness) => {
    try {
        await ElMessageBox.confirm(`确定要删除该业务吗？`, '删除业务', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        if (!row?.id) {
            ElMessage.error('缺少业务ID，无法删除')
            return
        }

        await deleteGenBusiness(Number(row.id))
        ElMessage.success('删除成功')
        refreshData()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }
}

// 页面初始化
onMounted(() => {
    getData()
})
</script>

<style lang="scss" scoped></style>